package com.deductive.netty.udp;

import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class UdpClientManager {

    private final ConcurrentMap<String, InetSocketAddress> userAddressMap = new ConcurrentHashMap<>();
    private final ConcurrentMap<InetSocketAddress, String> addressUserMap = new ConcurrentHashMap<>();

    /**
     * 注册一个新的UDP客户端
     *
     * @param userId  用户ID
     * @param address 客户端的Socket地址 (IP + Port)
     */
    public void registerClient(String userId, InetSocketAddress address) {
        userAddressMap.put(userId, address);
        addressUserMap.put(address, userId);
    }

    /**
     * 移除一个UDP客户端
     *
     * @param address 客户端的Socket地址
     */
    public void removeClient(InetSocketAddress address) {
        String userId = addressUserMap.remove(address);
        if (userId != null) {
            userAddressMap.remove(userId);
        }
    }

    /**
     * 根据用户ID获取其地址
     *
     * @param userId 用户ID
     * @return 客户端的Socket地址
     */
    public InetSocketAddress getAddress(String userId) {
        return userAddressMap.get(userId);
    }

    /**
     * 获取所有已知的用户ID
     *
     * @return 用户ID集合
     */
    public Set<String> getAllUserIds() {
        return userAddressMap.keySet();
    }
}

